﻿namespace ChinaUnicom.Parser.Parsers
{
    using ChinaUnicom.Models;
    using HtmlAgilityPack;
    using System.Linq;

    internal class FeeParser : IItemsParser
    {
        public ItemType Type
        {
            get { return ItemType.Fee; }
        }

        public ItemCollection Parse(string html)
        {
            ItemCollection items = new ItemCollection();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html.Replace("&nbsp;", string.Empty));

            var node = doc.DocumentNode;// .ChildNodes.Select(x=>x.Attributes["class"].Value == "nrong")

            var div = node.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "nrong").FirstOrDefault();

            if (div != null)
            {
                var p = div.Descendants("p").SingleOrDefault();

                int step = -1;

                if (p != null)
                {
                    string name = string.Empty;
                    foreach (HtmlNode n in p.ChildNodes)
                    {
                        if (n.Name == "#text" && n.InnerText.InnerTextTrim().Contains("当月话费信息"))
                        {
                            step = 0;
                            continue;
                        }
                        else if (n.Name == "#text" && n.InnerText.InnerTextTrim().Contains("当月话费明细"))
                        {
                            step = 1;
                            continue;
                        }

                        if (step >= 0)
                        {
                            if (n.Name == "#text" && string.IsNullOrEmpty(name))
                            {
                                name = n.InnerText.InnerTextTrim();
                            }

                            if (n.Name == "span" && !string.IsNullOrEmpty(name))
                            {
                                items.Add(new Item { Name = name, Value = n.InnerText.InnerValueTrim() });
                                name = string.Empty;
                            }
                        }
                    }
                }
            }

            return items;
        }
    }
}
